//
//  NSString+Encrypt.m
//  Test
//
//  Created by lizq on 15/8/18.
//  Copyright (c) 2015年 lizq. All rights reserved.
//

#import "NSString+Encrypt.h"
#import <CommonCrypto/CommonCrypto.h>
#import "GTMBase64.h"
@implementation NSString (Encrypt)

- (NSInteger)UTF8Length {
     NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < self.length; i++) {
        unichar uc = [self characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger utf8Length = asciiLength / 2;
    if(asciiLength % 2) {
        utf8Length++;
    }
    return utf8Length;
}

//MD5 Sring
- (NSString *)md5String {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    const char *value = [self UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return outputString;
}

//Base64 Encode
- (NSString *)base64Encode {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    data = [data base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result;
}

//Base64 Decode
- (NSString *)base64Decode {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result;
}

- (NSString *)aesEncryptWithKey:(NSString *)key {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    return [self encrypt:self algorithm:kCCAlgorithmAES128 operation:kCCEncrypt keySize:kCCKeySizeAES128 key:key];
}

- (NSString *)aesDecryptWithKey:(NSString *)key {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    return [self encrypt:self algorithm:kCCAlgorithmAES128 operation:kCCDecrypt keySize:kCCKeySizeAES128 key:key];
}

//DES 加密
- (NSString *)desEncryptWithKey:(NSString *)key {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    return [self encrypt:self algorithm:kCCAlgorithmDES operation:kCCEncrypt keySize:kCCKeySizeDES key:key];
}
//DES 解密
- (NSString *)desDecryptWithKey:(NSString *)key {
    if(self == nil || [self length] == 0) {
        return nil;
    }
    return [self encrypt:self algorithm:kCCAlgorithmDES operation:kCCDecrypt keySize:kCCKeySizeDES key:key];
}

- (NSString *)encrypt:(NSString *)sText algorithm:(CCAlgorithm)agl operation:(CCOperation)op keySize:(NSInteger)keySize key:(NSString *)key {
    
    const void *dataIn;
    size_t dataInLength;
    if (op == kCCDecrypt) {
        //传递过来的是decrypt 解码
        //解码 base64
        NSData *decryptData = [GTMBase64 decodeData:[sText dataUsingEncoding:NSUTF8StringEncoding]];//转成utf-8并decode
        dataInLength = [decryptData length];
        dataIn = [decryptData bytes];
    }else {
        //encrypt
        NSData* encryptData = [sText dataUsingEncoding:NSUTF8StringEncoding];
        dataInLength = [encryptData length];
        dataIn = (const void *)[encryptData bytes];
    }
    
    /*
     DES加密 ：用CCCrypt函数加密一下，然后用base64编码下，传过去
     DES解密 ：把收到的数据根据base64，decode一下，然后再用CCCrypt函数解密，得到原本的数据
     */
    CCCryptorStatus ccStatus;
    uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写（有效的维护了代码，比如：一个人用int，一个人用long。最好用typedef来定义）
    size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型
    size_t dataOutMoved = 0;
    if(keySize == kCCKeySizeDES) {
        dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    }
    if(keySize == kCCKeySizeAES128) {
        dataOutAvailable = dataInLength + kCCBlockSizeAES128;
    }
    dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 0x0, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0
    
    const void *vkey = (const void *) [key UTF8String];
    
    //CCCrypt函数 加密/解密
    ccStatus = CCCrypt(op,//  加密/解密
                       agl,//  加密根据哪个标准（des，3des，aes。。。。）
                       kCCOptionPKCS7Padding,//  选项分组密码算法(des:对每块分组加一次密  3DES：对每块分组加三个不同的密)
                       vkey,  //密钥    加密和解密的密钥必须一致
                       keySize,//   DES 密钥的大小（kCCKeySizeDES=8）
                       NULL, //  可选的初始矢量
                       dataIn, // 数据的存储单元
                       dataInLength,// 数据的大小
                       (void *)dataOut,// 用于返回数据
                       dataOutAvailable,
                       &dataOutMoved);
    NSString *result = nil;
    if (op == kCCDecrypt) {
        //encryptOperation==1  解码
        //得到解密出来的data数据，改变为utf-8的字符串
        result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding];
    }else {
        //encryptOperation==0  （加密过程中，把加好密的数据转成base64的）
        //编码 base64
        NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
        result = [GTMBase64 stringByEncodingData:data];
    }
    
    return result;
}

@end
